package com.yxt.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.sys.CommUtil;
import com.yxt.common.sys.StringUtil;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {
	private EditText txtuser;
	private EditText txtpassword;
	private CheckBox chkpassword;
	private CheckBox chkauto;
	private Button btnLogin;
	private Button btnExit;
	private ProgressDialog dialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		ActivityStackControlUtil.add(this);
		initComponent();// 初始化页面组件
		initValue();// 初始化组件值
		TextView lblTitle = (TextView)findViewById(R.id.lblTitle);
		lblTitle.setText("水情易信通");
		lblTitle.setTextSize(20);
	}
	
	public static void checkDirectoryIsExists(){
		File dbfile = new File(CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.DB_LOCATION);
		if (!dbfile.exists()) {
			dbfile.mkdirs();
		}
		File xmlfile = new File(CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.XML_LOCATION);
		if (!xmlfile.exists()) {
			xmlfile.mkdirs();
		}
		File photofile = new File(CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.PHOTO_LOCATION);
		if (!photofile.exists()) {
			photofile.mkdirs();
		}
		File htmlfile = new File(CommConstant.Config.DEFAULT_PHONE_DIR+CommConstant.Config.HTML_LOCATION);
		if (!htmlfile.exists()) {
			htmlfile.mkdirs();
		}
	}
	
	/**
	 * 初始化相关的控件
	 * 
	 * @author crazyman
	 */
	public void initComponent() {
		checkDirectoryIsExists();
		
		txtuser = (EditText) findViewById(R.id.txtUserName);
		txtpassword = (EditText) findViewById(R.id.txtPassword);
		chkpassword = (CheckBox) findViewById(R.id.chkPassword);
		chkauto = (CheckBox) findViewById(R.id.chkAutoLogin);
		chkpassword.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (!chkpassword.isChecked())
					chkauto.setChecked(false);
			}
		});
		chkauto.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (chkauto.isChecked())
					chkpassword.setChecked(true);
			}
		});
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog = ProgressDialog.show(LoginActivity.this, "系统登录",
						"登录中,请稍后....", true, true);
				// 开一个线程进行登录验证,主要是用于失败,成功可以直接通过startAcitivity(Intent)转向
				Thread loginThread = new Thread(new LoginHandler());
				loginThread.start();
			}
		});
		btnExit = (Button) findViewById(R.id.btnExit);
		btnExit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
	}

	private class LoginHandler implements Runnable {
		public void run() {
			if (login()) {
				saveParameters();
				
				WindowManager windowManager = getWindowManager();
				Display display = windowManager.getDefaultDisplay();
				CommConstant.screenWidth = display.getWidth();
				CommConstant.screenHeight = display.getHeight();

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行FLAG设置 
				startActivity(intent);
				dialog.dismiss();
			}
		}
	}

	/**
	 * 初始化相关的值
	 * 
	 * @author crazyman
	 */
	public void initValue() {
		SharedPreferences settings = getSharedPreferences(
				CommConstant.Login.APP_KEY, Context.MODE_PRIVATE);
		// 获取相关属性的值
		String name = settings.getString(CommConstant.Login.APP_USERNAME, "");
		String password = settings.getString(
				CommConstant.Login.APP_AUTO_PASSWORD, "");
		String autopassword = settings.getString(
				CommConstant.Login.APP_PASSWORD, "");
		String autologin = settings.getString(
				CommConstant.Login.APP_AUTO_LOGIN, "");
		// 设置到页面组件中
		txtuser.setText(name);
		txtpassword.setText(password);
		if (!StringUtil.isEmpty(autopassword))
			chkpassword.setChecked(true);
		if (!StringUtil.isEmpty(autologin))
			chkauto.setChecked(true);
		// 判断是否为自动登录,如果为自动登录则调用登录方法
		if (!StringUtil.isEmpty(autopassword) && !StringUtil.isEmpty(autologin)) {
			dialog = ProgressDialog.show(LoginActivity.this, "系统登录", "登录中,请稍后....",
					true, true);
			// 开一个线程进行登录验证,主要是用于失败,成功可以直接通过startAcitivity(Intent)转向
			Thread loginThread = new Thread(new LoginHandler());
			loginThread.start();
		}
	}

	/**
	 * 保存相关的数据
	 * 
	 * @author crazyma
	 */
	public void saveParameters() {
		SharedPreferences settings = getSharedPreferences(CommConstant.Login.APP_KEY, Context.MODE_PRIVATE);
		Editor editor = settings.edit();
		// 获取相关的数据
		String user = txtuser.getText().toString();
		String password = txtpassword.getText().toString();
		String autopassword = chkpassword.getText().toString();
		String autologin = chkauto.getText().toString();
		// 设置数据到SharedReference中
		editor.putString(CommConstant.Login.APP_USERNAME, user);
		if (chkpassword.isChecked()) {
			editor.putString(CommConstant.Login.APP_PASSWORD, password);
			editor.putString(CommConstant.Login.APP_AUTO_PASSWORD,autopassword);
		} else {
			editor.putString(CommConstant.Login.APP_PASSWORD, "");
			editor.putString(CommConstant.Login.APP_AUTO_PASSWORD, "");
		}
		//判断是否选中
		if (chkauto.isChecked()) {
			editor.putString(CommConstant.Login.APP_AUTO_LOGIN, autologin);
		} else {
			editor.putString(CommConstant.Login.APP_AUTO_LOGIN, "");
		}
		//保存数据到文件
		if ("".equals(settings.getString(CommConstant.Login.APP_TEMPLATE_CODE, ""))){
			CommUtil.persistenceTemplateInfo(getApplicationContext());
		} else {
			CommConstant.Main.CURRENT_TEMPLATE_CODE = settings.getString(CommConstant.Login.APP_TEMPLATE_CODE, "");
			CommConstant.Main.CURRENT_TEMPLATE_NAME = settings.getString(CommConstant.Login.APP_TEMPLATE_NAME, "");
		}
		if ("".equals(settings.getString(CommConstant.Login.APP_AREA_CODE, ""))){
			CommUtil.persistenceAreaInfo(getApplicationContext());
		} else {
			CommConstant.Main.CURRENT_AREA_CODE = settings.getString(CommConstant.Login.APP_AREA_CODE, "");
			CommConstant.Main.CURRENT_AREA_NAME = settings.getString(CommConstant.Login.APP_AREA_NAME, "");
		}
		if ("".equals(settings.getString(CommConstant.Login.APP_RIVER_CODE, ""))){
			CommUtil.persistenceRiverInfo(getApplicationContext());
		} else {
			CommConstant.Main.CURRENT_RIVER_CODE = settings.getString(CommConstant.Login.APP_RIVER_CODE, "");
			CommConstant.Main.CURRENT_RIVER_NAME = settings.getString(CommConstant.Login.APP_RIVER_NAME, "");
		}
		editor.commit();
	}

	/**
	 * 登录方法
	 * 
	 * @author crazyman
	 * @return 是否成功
	 */
	public boolean login() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new FunctionHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}
		return true;
	}
	
	private InputStream getInputStream() throws IOException{
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION + "android.xml");
		} else {
			//获取手机唯一标识
			//CommConstant.Main.CURRENT_IPHONE_CODE = CommUtil.getMachineId(getApplicationContext());
			URL url = new URL("http://pda.hydroinfo.gov.cn/newpda/init/CheckUser.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&river=");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}

	private class FunctionHandler extends DefaultHandler {
		private String code;

		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {
			if ("username".equals(localName)) {
				
			} else if ("template".equals(localName)) {
				code = attrs.getValue("code");
				Map<String, String> template = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					template.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				CommConstant.Main.TEMPLATES.put(code, template);
				CommConstant.Main.TEMPLATE_MAP.put(attrs.getValue("name"),code);
			} else if ("function".equals(localName)) {
				Map<String, String> data = new HashMap<String, String>();
				for (int i = 0; i < attrs.getLength(); i++) {
					data.put(attrs.getLocalName(i), attrs.getValue(i));
				}
				String key = data.get("id");
				if (CommConstant.Main.FUNCTIONS.containsKey(code)) {
					CommConstant.Main.FUNCTIONS.get(code).put(key, data);
				} else {
					Map<String,Map<String,String>> functions= new HashMap<String,Map<String,String>>();
					functions.put(key, data);
					CommConstant.Main.FUNCTIONS.put(code, functions);
				}
			}else if ("message".equals(localName)) {
				if (attrs.getValue("info").contains("失败")) {
					dialog.cancel();
					throw new RemoteServerException(attrs.getValue("info"));
				}
			}
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {  
		if(keyCode == KeyEvent.KEYCODE_BACK){
			return false;
		}
		return super.onKeyDown(keyCode, event); 
	}
	
	protected void onDestroy() {
		super.onDestroy();
        ActivityStackControlUtil.remove(this);
	}
}